<template>
  <AppDialogForm
    :title="props.catInfo.cat_id ? '编辑分类' : '添加分类'"
    :confirm="handleSubmit"
    @closed="handleDialogClosed"
    @open="handleDialogOpen"
  >
    <el-form
      ref="form"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="loading"
    >
      <el-form-item label="分类名称：" prop="cat_name">
        <el-input v-model="formData.cat_name"></el-input>
      </el-form-item>
      <el-form-item label="父级分类：" v-if="!props.catInfo.cat_id">
        <!--props用来指定配置对象-->
        <el-cascader
          v-model="selectedKeys"
          :options="parentCateList"
          :props="cascaderProps"
          @change="parentCateChange"
          clearable
        ></el-cascader>
      </el-form-item>
    </el-form>
  </AppDialogForm>
</template>

<script setup>
import { ref, nextTick } from "vue";
import { ElMessage } from "element-plus";
import { getCategoriesList, addCategories, editCategories } from "@/api/categories.js";

const props = defineProps({
  catInfo: {
    type: Object,
    default: () => {},
  }
});
const emit = defineEmits(["success"]);
const form = ref(null);
const loading = ref(false);
const formData = ref({
  cat_name: "",
  cat_pid: 0,  //父级分类的ID
  cat_level: 0 //分类层级
});
const formRules = {
  cat_name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
};
const parentCateList = ref([])
const cascaderProps = {  //指定级联选择器的配置对象
  expandTrigger: 'hover',
  checkStrictly: true,  //可选任意一项
  value: 'cat_id',
  label: 'cat_name',
  children: 'children'
}
const selectedKeys = ref([]) //选中父级分类ID数组

const loadInfo = () => {
  if (!props.catInfo.cat_id) {
    return;
  }
  formData.value = { ...props.catInfo };
};

const handleDialogOpen = async () => {
  if (!props.catInfo.cat_id) {
    const queryInfo = {type: 2}
    const data = await getCategoriesList(queryInfo)
    parentCateList.value = data
  }
  loadInfo();
};

const parentCateChange = () => {
  nextTick(() => {
  // 如果selectedKeys数组中的length大于0，则表示选中父级分类
  // 反之就表示没有选中任何父级
  if (selectedKeys.value && selectedKeys.value.length > 0){
    // 父级分类ID
    formData.value.cat_pid = selectedKeys.value[selectedKeys.value.length-1];
    // 当前分类等级
    formData.value.cat_level = selectedKeys.value.length;
  }else {
    // 父级分类ID
    formData.value.cat_pid = 0;
    // 当前分类等级
    formData.value.cat_level = 0;
  }
  })
}

const handleSubmit = async () => {
  const valid = await form.value.validate();
  if (!valid) {
    return;
  }
  loading.value = true;
  if (props.catInfo.cat_id) {
    const data = {
      cat_name: formData.value.cat_name
    }
    // 更新
    await editCategories(props.catInfo.cat_id, data).finally(() => {
      loading.value = false;
    });
    ElMessage.success("编辑成功");
  } else {
    // 添加
    await addCategories(formData.value).finally(() => {
      loading.value = false;
    });
    ElMessage.success("添加成功");
  }
  emit("success");
};
const handleDialogClosed = () => {
  form.value.clearValidate(); // 清除验证结果
  form.value.resetFields(); // 清除表单数据
  formData.value = {
    cat_name: "",
    cat_pid: 0,
    cat_level: 0
  };
  selectedKeys.value = []
};
</script>

<style lang="scss" scoped></style>
